Nuxt の $fetch() と useFetch() と useAsyncData() をさらっと学ぶ in 202512
何回勉強しても良いとされる Nuxt の $fetch, useFetch(), useAsyncData() In a nutshell:
$fetch is the simplest way to make a network request.
useFetch is a wrapper around $fetch that fetches data only once in universal rendering.
useAsyncData is similar to useFetch but offers more fine-grained control.
雑な感想
命名でなんとなくわかる雰囲気としては、
$fetch
結構 primitive な関数、本当に data fetch のみを simple に行う
それを多分いい感じに使いやすくしてくれているやつ
useFetch()
Nuxt の applicatation を書く上で、いい感じに fetch を扱うことができる useAsyncData()
async data と言っているので fetch よりももっと抽象的な印象
The need for useFetch() and useAsyncData()
この問題を解決するのが useFetch() と useAsyncData()
これらを使用することで servert 側で fetch して、 payload につめて client に渡す payload は JavaScript の object で useNuxtApp().payload で accsess できる これを使用することで client 側で refetch とか hydration 中に browser で実行されるのを防ぐ
code:vue
<script setup lang="ts">
const { data } = await useFetch("/api/data");
async function handleFormSubmit () {
const res = await $fetch("/api/submit", {
method: "POST",
body: { /* My Form Data */ },
});
}
</script>
<template>
<div v-if="data == undefined">
No Data
</div>
<div v-else>
<form @submit="handleFormSubmit">
<!-- Form Inputs -->
</form>
</div>
</template>
⬆️の例だと、useFetch() を使うことで data fetch が確実に server 側で行われる
$fetch() はそんな仕組みがないので browswer 側で単に fetch したいときに使用する
useAsyncData() をざっくり
useFetch(url) is nearly equivalent to useAsyncData(url, () => event.$fetch(url)).
It's developer experience sugar for the most common use case. (You can find out more about event.fetch at useRequestFetch.)
https://youtu.be/0X-aOpSGabA